/**
 * CREATE TABLE users (
 id INT PRIMARY KEY AUTO_INCREMENT,
 username VARCHAR(50) NOT NULL,
 email VARCHAR(100) UNIQUE NOT NULL,
 password VARCHAR(255) NOT NULL,
 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 is_active BOOLEAN DEFAULT TRUE
 );
 */

/**
 * 描述一个字段
 * 1,字段在数组中的顺序就是在表中的顺序需要保持一致.
 */

export class Field {
  name: string
  type: FieldType
  primaryKey: boolean = false;
  autoIncrement: boolean = false;

  constructor(name: string, type: FieldType) {
    this.name = name;
    this.type = type;
  }
}

/**
 * 根据typeof的返回值,返回对应的sqlite字段类型
 * @param type
 */
export function fieldTypeFromTypeString(type: string) {
  switch (type) {
    case 'Text':
      return FieldType.String;
    case 'INTEGER':
      return FieldType.Int
    default:
      return FieldType.String;
  }
}

export enum FieldType {
  Int = "INTEGER",
  String = "TEXT",
}

export function createTable(name: string, fileds: Field[]) {
  let sql = `CREATE TABLE ${name} IF NOT EXISTS`;
  const filedInfos = fileds.map(f => generateFiledString(f));
  sql += ` ${filedInfos.join(" , ")}`
  return sql;
}

/**
 * 为一个字段生成一个filed
 * @param f
 */
export function generateFiledString(f: Field) {
  let str = `${f.name} ${f.type}`;
  if (f.primaryKey) {
    str += ` PRIMARY KEY`
  }
  if (f.autoIncrement) {
    str += ` AUTOINCREMENT`
  }
  return str;
}